package com.zhengb.nettydemos.chapter4.timeserver;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Currency;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhengbo on 2019/4/2.
 */
//@Slf4j
public class TimeServerHandler extends ChannelHandlerAdapter {

    private static AtomicInteger counter = new AtomicInteger(0);

    private static Logger logger = LoggerFactory.getLogger(TimeServerHandler.class);

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

//        ByteBuf byteBuf = (ByteBuf) msg;
//
//        byte[] req = new byte[byteBuf.readableBytes()];

//        byteBuf.readBytes(req);

//        String body = new String(req, StandardCharsets.UTF_8).substring(
//                0, req.length - System.getProperty("line.separator").length()
//        );

        String body = (String) msg;
        logger.info("The time server recieve order:{},the counter is:{}", body, counter.incrementAndGet());

        boolean rightRequestMessage = "request server time".equalsIgnoreCase(body);
        String currentTime = rightRequestMessage ? LocalDateTime.now().toString() : "bad request";
        currentTime = currentTime + System.getProperty("line.separator");

        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.writeAndFlush(resp);
    }
}
